package models

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/chaosue/echo-sessions"
	"github.com/labstack/echo"
)

// 映射聚美auth.api 里的person
type User struct {
	Username   string `json:"username"`
	Success    bool   `json:"success"`
	Mobile     string `json:"mobile"`
	Department string `json:"department"`
	Mail       string `json:"mail"`
	Fullname   string `json:"fullname"`
	IsManager  bool   `json:"is_manager"`
}

type UserWithPirvilege struct {
	User
	PrivilegeList []*TPrivilege `json:"privilege_list"`
}
type MemberListStruct struct {
	Message   string           `json:"message"`
	Members   []string         `json:"members"`
	Success   bool             `json:"success"`
	Details   map[string]*User `json:"details"`
	IsManager bool             `json:"is_manager"`
}

type UserGroupStruct struct {
	Members map[string][]string `json:"members"`
	Groups  []string            `json:"groups"`
}

var UserGroup UserGroupStruct

// CheckRole 检查用户是否登录
func CheckLogin(c echo.Context) UserWithPirvilege {
	session := sessions.Default(c)
	currentObj := session.Get(SESSION_USER)
	if currentObj == nil {
		panic(errors.New("尚未登陆"))
	}
	currentUser := currentObj.(User)
	var userWithPirvilege UserWithPirvilege
	userWithPirvilege.User = currentUser
	userWithPirvilege.PrivilegeList = AllUserPrivilegeList[currentUser.Username]
	return userWithPirvilege
}

func LoadAllUser() (err error) {
	params := fmt.Sprintf("?app_key=%s&app_name=%s", Conf.AppInfo.AppKey, Conf.AppInfo.Appname)
	var request *http.Request
	request, err = http.NewRequest(http.MethodGet, Conf.JumeiAuth.JumeiAuthUrl+API_GROUP_URL+params, nil)

	if err != nil {
		return
	}
	client := new(http.Client)
	var respo *http.Response
	respo, err = client.Do(request)
	defer respo.Body.Close()
	var responseBody []byte
	responseBody, err = ioutil.ReadAll(respo.Body)
	err = json.Unmarshal(responseBody, &UserGroup)
	return
}

func IsManager(username string) bool {

	for _, nameItem := range UserGroup.Members[Conf.AcsGroup.Acs_manage_group] {
		if nameItem == username {
			return true
		}
	}
	return false
}
